package lab4.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;


import javax.servlet.*;
import javax.servlet.http.*;

/**
 * Servlet implementation class Search
 */
public class Search extends HttpServlet {
	private static final long serialVersionUID = 1L;  
    public Search() {
        super();        
    }
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
		doSearch(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
		throws ServletException, IOException {
		System.out.println("search访问");
		//doSearch(request,response);
	}
	public void doSearch(HttpServletRequest request, HttpServletResponse resp) throws IOException 
	{
		try{
		Class.forName("org.hsqldb.jdbcDriver");
		Connection connection = DriverManager.getConnection("jdbc:hsqldb:hsql://localhost/xdb", "sa", "");
		PreparedStatement ps=connection.prepareStatement("select * from usr where name like ?");
		String nameToSearch=request.getParameter("key");
		ps.setString(1,nameToSearch+"%");
		ResultSet rs=ps.executeQuery();
		
		  resp.setContentType("text/html"); 

	        PrintWriter out = resp.getWriter(); 

	        out.println(" <html> <body> <h1>Search Result:</h1> <p><hr> "); 
	        out.println("<table border='1'><tr><td>ID</td><td>name</td><td>password</td></tr>");
	        int n=0;
	        for(;rs.next();)
	        {
	        	out.println("<tr><td>");
	        	out.println(rs.getString(1));
	        	out.println("</td><td>");
	        	out.println(rs.getString(2));
	        	out.println("</td><td>");
	        	out.println(rs.getString(3));
	        	out.println("</td></tr>");
	        	n++;	        	
	        }
	        out.println("</table><hr>");
	        out.println("You got "+n+" records."); 
	        out.println("</p> <hr><a href=\"index.html\">search again</a> </body> </html> "); 		
		}catch(Exception ex)
		{
			//.println(ex.printStackTrace(s) ex.toString());
			ex.printStackTrace(resp.getWriter());
			ex.printStackTrace();
		}

	}

}
